package com.itheima.work;

import java.util.concurrent.CountDownLatch;

/**
 * @auther Macrydy
 * @date 2020/7/9 18:58
 *    请使用CountDownLatch编写一个程序，实现以下效果：
 *
 * ​       线程A打印：”开始计算”
 *
 * ​       线程B：计算1--100所有数的累加和，并打印结果。
 *
 * ​       线程A打印：”计算完毕”
 */
public class Test3 {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        A a = new A(countDownLatch);
        B b = new B(countDownLatch);
        b.start();
        a.start();
    }
}
class A extends Thread{
    private CountDownLatch countDownLatch;

    public A(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("开始计算");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("计算完毕");
    }
}
class B extends Thread{
    private CountDownLatch countDownLatch;

    public B(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getSum(100));
        countDownLatch.countDown();
    }

    private int getSum(int i) {

        if (i==1){
            return 1;
        }else {
            return i + getSum(i - 1);
        }
    }
}